package com.neuedu.his.utils;

import com.neuedu.his.common.utils.DBUtils;
import com.neuedu.his.generator.EntityProp;
import com.neuedu.his.generator.InsertProp;
import com.neuedu.his.generator.PkProp;
import com.neuedu.his.generator.TableColumn;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FreeMarkerUtils {
    Configuration cfg = null;
    //        String dir = "D:\\workspace\\his\\his-server\\src\\main\\java";
    String dir = "C:\\Users\\Administrator\\Desktop\\dir";
    String basePackage = "com.neuedu.his";

    @Before
    public void init() {
        cfg = new Configuration(Configuration.VERSION_2_3_22);
        //获取测试执行的时候的 class目录
        //获取ClassLoader
        URL resource = Thread.currentThread().getContextClassLoader().getResource(".");
//            System.out.println("resource.getPath() = " + resource.getPath());
        //动态获取   template目录
        try {
            cfg.setDirectoryForTemplateLoading(new File(resource.getPath()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    }


    @Test
    public void run() throws FileNotFoundException {


        try {
            Connection connection = DBUtils.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet tables = metaData.getTables("his", "his", null, new String[]{"TABLE"});

//            ResultSetMetaData metaData1 = tables.getMetaData();

            while (tables.next()) {
                String tableName = tables.getString("TABLE_NAME");
                System.out.println(tableName);
                generatorOne(connection,tableName);
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }




    }



    public void generatorOne(Connection conn , String tableName){


        //构造数据
        Map data = generatorData(conn, tableName);



        String entityPack = (String) data.get("entityPackage");
        String daoPackage = (String) data.get("daoPackage");
        String servicePack = (String) data.get("servicePack");
        String controllerPack = (String) data.get("controllerPack");


        String className = (String) data.get("className");

        String tempName = "JavaBean.ftl";
        generator( tempName, data,entityPack,className+".java");

        String ignoreTable = "role_menu,user_role,";

        if(ignoreTable.indexOf(tableName)!=-1){
            return;
        }



        tempName = "Dao.ftl";
        generator(tempName, data,daoPackage,className+"Dao.java");

        tempName = "Service.ftl";
        generator(tempName, data,servicePack,className+"Service.java");

        tempName = "Controller.ftl";
        generator(tempName, data,controllerPack,className+"Controller.java");
    }






    public void generator( String tempName, Object data,String pack,String padding) {
        File file =new File(dir+"\\"+pack.replaceAll("\\.","\\\\")+  "\\"+padding);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }

        Template temp = null;
        try {
            OutputStream out =  new FileOutputStream(file) ;

            System.out.println("生成文件："+file.getName());
            temp = cfg.getTemplate("template/" + tempName);
            //输出到流
            temp.process(data, new OutputStreamWriter(out));
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }

    }


    private Map generatorData(Connection conn ,  String tableName) {
        Map<String, Object> root = new HashMap<>();
        //实体类名
        root.put("tableName", tableName);
        root.put("className", table2Class(tableName));

        //实体的报名
        root.put("entityPackage", "com.neuedu.his.entity");
        root.put("daoPackage", "com.neuedu.his.dao");
        root.put("servicePack", "com.neuedu.his.service");
        root.put("controllerPack", "com.neuedu.his.controller");


        List<TableColumn> tableColumns = getTableColumns(conn, tableName);


        List entityProps = new ArrayList<>();

        for (TableColumn tableColumn : tableColumns) {
            entityProps.add(new EntityProp(
                    tableColumn.getJavaType(),
                    tableColumn.getEntityPropName(),
                    tableColumn.getColumnName(),
                    tableColumn.getColumnComment()));
        }

//        entityProps.add(new EntityProp("String","dname"));
//        entityProps.add(new EntityProp("String","loc"));

        root.put("entityProps", entityProps);

        //insertProps

        List insertProps = new ArrayList();
        List updateProp = new ArrayList();
        String ignoreInsertColumn = "del,createtime";
        String ignoreUpdateColumn = "createtime";
        for (TableColumn tableColumn : tableColumns) {
            if(!"PRI".equals(tableColumn.getColumnKey())){
                //del,createTime
                if(ignoreInsertColumn.indexOf(tableColumn.getColumnName()) == -1){
                    insertProps.add(new InsertProp(tableColumn.getEntityPropName(),tableColumn.getColumnName()));
                }
                if(!ignoreUpdateColumn.equals(tableColumn.getColumnName())){
                    updateProp.add(new InsertProp(tableColumn.getEntityPropName(),tableColumn.getColumnName()));
                }
            }else{
                PkProp pkProp = new PkProp(tableColumn.getEntityPropName(),tableColumn.getColumnName());
                root.put("pkProp",pkProp);
            }
        }
        root.put("insertProps", insertProps);
        root.put("updateProp", updateProp);




        return root;
    }


    /**
     * 表名转换成  类名
     * @param tablename
     * @return
     */
    public String table2Class(String tablename){
        String classname = "";
        if(tablename.contains("_")){
            String split[] = tablename.split("_");
            classname = split[0].substring(0,1).toUpperCase() +split[0].substring(1,split[0].length())
                    +   split[1].substring(0,1).toUpperCase() +split[1].substring(1,split[1].length());
        }else{
            classname = tablename.substring(0,1).toUpperCase() +tablename.substring(1,tablename.length());
        }
        return classname;
    }



    public List<TableColumn> getTableColumns(Connection connection, String tableName) {

        String sql = "  SELECT column_name, ordinal_position ,data_type,column_key ,column_comment from information_schema.COLUMNS t WHERE  TABLE_SCHEMA='his'  and      table_name='"+tableName+"'  ORDER BY ordinal_position";
        List<TableColumn> list  = new ArrayList<>();
        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);

            while (resultSet.next()){
                String column_name = resultSet.getString("column_name");
                String ordinal_position = resultSet.getString("ordinal_position");
                String data_type = resultSet.getString("data_type");
                String column_key = resultSet.getString("column_key");
                String column_comment = resultSet.getString("column_comment");

                list.add(new TableColumn(column_name,
                        ordinal_position,
                        data_type,
                        column_key,
                        column_comment ));

            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return  list;
    }


}